<template>
  <div class="box">
    <TopSearch @searchHeader="searchHeader" @delsHeader="delsHeader" @headerButtonDel="headerButtonDel"
      @headerButtonSearch="headerButtonSearch" @headerButtonSelect="headerButtonSelect" :control="control"
      :controlPosition="controlPosition" :positionName="positionName" :disabled="disabled" :delsable="delsable"
      :searchConfig="setFormConfig">
      <template #add><el-button @click="addHeader" v-permission="'student/create'" color="#50BC58" icon="Plus" circle
          class="ml-4 button"></el-button></template>
      <template #DataImport>
        <el-button class="ml-10" color="#2292A4" @click="excelClick" icon="Download">數據導入</el-button>
      </template>
    </TopSearch>
    <ProTable class="protable" :data="tableData" :page="page" :column="column" :rowControl="rowControl"
      :elProps="elProps" :disabled="disabled" :controlWidth="controlWidth" @row-control-click="onRowControlClick"
      @selection-change="onSelectionChange" @page-change="onPageChange" @pageRefresh="pageRefresh">
      <template #default="{ row, propname }">
        <div v-if="propname === 'school' || propname === 'cate'">
          {{ row[propname] && row[propname].name ? row[propname].name : row[propname] }}
        </div>
      </template>

      <template #operateone>
        <el-table-column fixed="right" min-width="200px" label="聯絡人">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="lookperson(scope.$index, scope.row)">查看聯絡人</el-link>
          </template>
        </el-table-column>
      </template>
      <template #search_operate>
        <el-table-column fixed="right" min-width="200px" label="操作">
          <template #default="scope">
            <div class="flex justify-around">
              <el-link v-permission="'student/update'" @click="onRowControlClick(scope.row, 'rowedit')" type="primary"
                :underline="false">查看</el-link>
              <el-link @click="onRowControlClick(scope.row, 'rowAddInvoice')" type="primary"
                :underline="false">新增發票</el-link>
              <el-link v-permission="'student/delete'" @click="onRowControlClick(scope.row, 'rowdel')" type="primary"
                :underline="false">刪除</el-link>
            </div>
          </template>
        </el-table-column>
      </template>
      <!-- <template #school="{ row, propname }">
          <div  v-if="propname === 'school'">{{row[propname].name}}</div>
      </template> -->

    </ProTable>

    <FouDialog :title="'添加/編輯'" :width="'95%'" v-model:dialogValue="dialogValue">
      <!-- <el-dialog
    v-model="dialogValue"
    title="新增學生"
    width="75%"
    :before-close="handleClose"
  > -->
      <template #content>
        <el-tabs type="card" class="tabs" @tab-click="handleClick" v-model="activeName">
          <el-tab-pane label="學生資料" name="Information">
            <el-button v-if="buttonType == 'add'" class="button" icon="Share" type="primary" color="#50BC58"
              @click="copy">分享鏈接</el-button>
            <addEdit :rules="rules" class="mt-[20px]" :studentTypeList="studentTypeList" :buttonType='buttonType'
              :echo="echo" ref="AddEditref" @addConfirm="addConfirm" @addCancal="dialogValue = false"></addEdit>
          </el-tab-pane>

          <el-tab-pane label="發票" name="invoice" v-if="buttonType == 'edit'">
            <invoiceList ref="invoiceRef" :echo="echo"></invoiceList>
          </el-tab-pane>
          <el-tab-pane label="消費" name="consumption" v-if="buttonType == 'edit'">
            <consumption ref="consumptionRef" :echo="echo"></consumption>
          </el-tab-pane>
          <el-tab-pane label="欠款" name="arrears" v-if="buttonType == 'edit'">
            <StudentPA ref="StudentpaRef" :echo="echo"></StudentPA>
          </el-tab-pane>
          <el-tab-pane label="調堂" name="hall" v-if="buttonType == 'edit'">
            <TuningHall ref="TuningHallRef" :echo="echo" :tableDataDT="tableDataDT"></TuningHall>
          </el-tab-pane>
          <el-tab-pane label="套票" name="ticket" v-if="buttonType == 'edit'">
            <ticketList ref="ticketRef" :echo="echo" :tableDataTP="tableDataTP"></ticketList>
          </el-tab-pane>
        </el-tabs>
        <div>
        </div>
      </template>
    </FouDialog>
    <FouDialog :title="'查看聯絡人'" :width="'50%'" v-model:dialogValue="personDialog">
      <template #content>
        <ProTable :data="personList" :column="personcolumn" :elProps="[]" :page="[]" :rowControl="[]" :disabled="[]"
          :controlWidth="[]">
        </ProTable>
      </template>
    </FouDialog>
    <!-- excel -->
    <FouDialog :title="'是否下載學生資料導入格式模板'" :width="'30%'" v-model:dialogValue="excelDiolog">
      <template #content>
        <div><el-icon>
            <WarningFilled />
          </el-icon>按照規定excel格式導入，可選擇下載當前模板進行格式對比，避免格式不正確導致數據丟失！注意：凡帶有(必填)字樣信息為必填，不填為空系統默以異常數據處理，帶有(參考)字樣需按照網站現有值進行填寫
        </div>
      </template>
      <template #footer>
        <el-button size="small" @click="onDownExcel">參考規則 (下載模板)</el-button>
        <el-button size="small" type="primary" @click="onImportExcel">已按照規定規則 (繼續導入)</el-button>
      </template>
    </FouDialog>
    <input v-show="false" type="file" accept=".xlsx,.xls" ref="inputUpload" @change="importExcel" />
    <FouDialog :title="'導入數據展示'" :width="'70%'" v-model:dialogValue="excelTableShow">
      <template #content>
        <excelTableList :excelTable="excelTable"></excelTableList>
      </template>
      <template #footer>
        <el-button @click="excelTableShow = false">取消</el-button>
        <el-button color="#081F42" @click="ImportStudent(excelTable)">確認導入</el-button>
      </template>
    </FouDialog>
    <addInvoice :echo="invoiceEcho" ref="AddInvoiceRef"></addInvoice>

  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from "vue"
import { elProps, controlWidth } from "./index.js"
import { setFormConfig } from "./formConfig";
import addEdit from './addEdit/index.vue'
import { studentList, delStudent, impStudent, studentType, getSign ,getTickets} from '@/http/index.js'
import { messageBox, message, loading, closeLoading } from '@/common/function.js'
import excelTableList from './excelTable.vue'
import { exportExcel } from '@/common/excel.js'
import useClipboard from 'vue-clipboard3'
import * as XLSX from "xlsx";
import invoiceList from './invoice/index.vue'
import addInvoice from '@/views/Invoices/invoice/addEdit/index.vue'
import consumption from './components/consumption.vue'
import StudentPA from './components/StudentPA.vue'
import ticketList from './components/ticketList.vue'
import TuningHall from './components/TuningHall.vue'
const excelData = [
  ['學生姓名(必填)', '電話(必填)', '登錄名(必填)', '密碼(必填)', '電子郵箱', '學生地址', '英文名', '學生來源', '備註', '性別(必填)', '狀態', '調課次數', '生日', '身份證', '學生類型(必填)', '學歷', '卡號(必填、十位數字)', '聯絡人名稱(必填)', '與學生關係(必填)', '聯絡人聯絡電話(必填)', '住宅電話', '聯絡人地址'],
  ['张三', '8***6952', 't**t', '123**456', '123@qq.com', '上海', 'zhangsan', '線下招生', '備註', '男', '現有', '1', '2023-05-19', '51399999*****65555', '常規課學生', '大學', '13245698', '李四', '朋友', '136****0000', '86451234', '上海'],
]; // 导出的表格名称
const onDownExcel = () => {
  exportExcel(excelData, '學生列表.xlsx', '學生')
  excelDiolog.value = false
}


const excelDiolog = ref(false)
const excelClick = () => {
  excelDiolog.value = true
}
const excelTable = ref([])
const excelTableShow = ref(false)
const importExcel = (file) => {
  // 获取上传的文件对象
  const { files } = file.target;
  // 通过FileReader对象读取文件
  const fileReader = new FileReader();
  fileReader.onload = (event) => {
    try {
      const { result } = event.target;
      // 以二进制流方式读取得到整份excel表格对象
      const workbook = XLSX.read(result, { type: "binary" });
      let data = []; // 存储获取到的数据
      // 遍历每张工作表进行读取（这里默认只读取第一张表）
      for (const sheet in workbook.Sheets) {
        if (Object.prototype.hasOwnProperty.call(workbook.Sheets, sheet)) {//这是关键的一步，hasOwnPropert要从Object的原型中调用
          // 利用 sheet_to_json 方法将 excel 转成 json 数据
          data = data.concat(
            XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
          );
          // break; // 如果只取第一张表，就取消注释这行
        }
      }
      console.log(data);
      let arr = []
      //  ['學生姓名(必填)','電話(必填)','登錄名(必填)','密碼(必填)','電子郵箱','學生地址','英文名','學生來源','備註','性別(必填)','狀態','調課次數(必填)','生日',
      //  '身份證','學生類型(必填)','學歷','卡號(必填、十位數字)','聯絡人名稱(必填)','與學生關係(必填)','聯絡人聯絡電話(必填)','住宅電話','聯絡人地址'],
      data.forEach(item => {
        let obj = {}
        obj.name = item["學生姓名(必填)"]
        obj.mobile = item["電話(必填)"]
        // obj.contact =obj.contact.push(item["聯絡人姓名(必填)"], item["與學生關係"],item['聯絡人聯絡電話']) 
        obj.contact = item["聯絡人(必填)"]
        obj.username = item["登錄名(必填)"]
        obj.password = item["密碼(必填)"]
        obj.email = item["電子郵箱"]
        obj.address = item["學生地址"]
        obj.ename = item["英文名"]
        obj.source = item["學生來源"]
        obj.remark = item["備註"]
        obj.sex = item["性別(必填)"] || item["性別"]
        obj.status = item["狀態"]
        obj.num = item["調課次數"]
        obj.birthday = item["生日"]
        obj.identity = item["身份證"]
        obj.student_type_id = item["學生類型(必填)"]
        obj.education = item["學歷"]
        obj.card_number = item["卡號(必填、十位數字)"]
        // obj.contact = JSON.stringify([item["聯絡人名稱(必填)"],item["與學生關係(必填)"],item["聯絡人聯絡電話(必填)"],item["住宅電話"],item["聯絡人地址"]])
        obj.contact = JSON.stringify([{
          name: item["聯絡人名稱(必填)"],
          relation: item["與學生關係(必填)"],
          phone: item["聯絡人聯絡電話(必填)"],
          homePhone: item["住宅電話"],
          address: item["聯絡人地址"],
        }])
        arr.push(obj)
      })
      arr.map(e => e.school_id = localStorage.getItem('school_id'))

      excelTable.value = arr

      excelTableShow.value = true
    } catch (e) {
      // 这里可以抛出文件类型错误不正确的相关提示
      console.log(e);
      message('文件类型不正确,請刷新後再試', "warning")
      return;
    }
  };
  // 以二进制方式打开文件
  fileReader.readAsBinaryString(files[0]);
}
const ImportStudent = async (e) => {
  const data = await impStudent(JSON.stringify(e))
  if (data.code == 200) {
    tableList()
    excelTableShow.value = false
  } else {
    message(data.msg, 'warning')
  }
  console.log(data);
}
const inputUpload = ref('')
const onImportExcel = () => {
  inputUpload.value.click()
  excelDiolog.value = false
}



const echo = ref({})

//搜索彈窗
const searchDiolog = ref(false);
const headerButtonSearch = () => {
  searchDiolog.value = true;
};

const searchDialog = (row, type) => {
  searchDiolog.value = false
}

// 添加編輯彈窗
const AddEditref = ref(null);
// const confirm = () => {
//   AddEditref.value.DialogCofirm();
// };
// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  statuss: "狀態",
  number: "學生編號",
  name: "學生名字",
  ename: "英文名字",
  birthday: "出生日期",
  mobile: "電話",
  address: '地址',
  email: '電郵地址',
  num: '可調課堂次數設定',
  card_number: "卡號",
  education: '學歷',
  identity: '身份證',
  sexs: '性別',
  school: '所屬學校',
  cate: '學生類型'
};
// 表格顶部操作按钮
const control = ["search", "dels"];
const controlPosition = [];
const positionName = ref("");

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const headerButtonDel = () => {
  console.log("headerButtonDel");
};

const headerButtonSelect = () => {
  console.log("headerButtonSelect");
};
const searchHeader = (e) => {
  Object.assign(obj, e);
  tableList(obj);
};
const rules = reactive({
  name: [{ required: true, message: "請輸入名字", trigger: ["blur", 'change'] }],
  mobile: [{ required: true, message: "請輸入電話", trigger: ["blur", 'change'] }],
  username: [{ required: true, message: "請輸入登錄名", trigger: ["blur", 'change'] }],
  password: [{ required: true, message: "請輸入密碼", trigger: ["blur", 'change'] }],
  sex: [{ required: true, message: "請選擇性別", trigger: ["blur", 'change'] }],
  // num: [{ required: true, message: "請輸入调课次数", trigger:  ["blur",'change']  }],
  student_type_id: [{ required: true, message: "請輸入學生類型", trigger: ["blur", 'change'] }],
  // card_number: [{ required: true, message: "請輸入卡號", trigger:  ["blur",'change']  }],
  contact: [{ required: true, message: "請添加联系人", trigger: ["blur", 'change'] }],
});
const dialogValue = ref(false);
const addHeader = async () => {
  echo.value = {
    status: 1
  }
  activeName.value = 'Information'
  buttonType.value = 'add'
  await studentTypes()
  dialogValue.value = true;
  rules.password = [{ required: true, message: "請輸入密碼", trigger: ["blur", 'change'] }]
};

// 表格行内操作按钮
const rowControl = ["rowedit", 'rowAddInvoice', "rowdel"];

/**表格行内操作
 * @row {object} 行内数据
 * @type {string} 点击按钮类型
 */
const buttonType = ref('')
const personList = ref([])
const personDialog = ref(false)
const personcolumn = {
  name: "名字",
  address: "地址",
  homePhone: "住宅電話",
  phone: "電話",
  relation: "與學生關係",
};
const AddInvoiceRef = ref('')
const invoiceEcho = ref({})
const onRowControlClick = async (row, type) => {
  console.log(row, type);
  if (type == 'rowedit') {
    await studentTypes()
    activeName.value = 'Information'
    dialogValue.value = true;
    buttonType.value = 'edit'
    const { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact } = row
    echo.value = { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact }
    echo.value.password = ''
    rules.password = [{ required: false }]
  }
  if (type == 'rowAddInvoice') {
    const { id, name } = row
    invoiceEcho.value = {
      student_id: id,
      student_name: name,
      status: '',
      remark: '',
      notice: '',
      course: [], //課程
      product: [], //產品
      products_group: [], //產品組合
      ticket: []//
    }

    AddInvoiceRef.value.dialogValue = true
    AddInvoiceRef.value.buttonType = 'add'
  }
  if (type == 'rowdel') {
    messageBox().then(async () => {
      await delTableList(row.id)
    });
  }

};

const activeName = ref('Information')
const invoiceRef = ref('')
const consumptionRef = ref('')
const StudentpaRef = ref('')
const ticketRef = ref('')
const TuningHallRef = ref('')
const handleClick = (tab, event) => {
  console.log(tab.props.name);
  // Information Invoice Consumption  arrears hall ticket
  if (tab.props.name == 'invoice') {
    invoiceRef.value.tableList()
  }
  if (tab.props.name == 'consumption') {
    consumptionRef.value.tableList()
  }
  if (tab.props.name == 'arrears') {
    StudentpaRef.value.init()
  }
  if (tab.props.name == 'hall') {
    TuningHallRef.value.init()
  }
  if (tab.props.name == 'ticket') {
    ticketRef.value.init()
  }

}
const delTableList = async (id) => {
  const data = await delStudent(id)
  if (data.code == 200) {
    tableList()
    message('已成功刪除該學生')
  } else {
    message('刪除該學生失敗')
  }
}
const lookperson = (index, row) => {
  personDialog.value = true
  personList.value = row.contact
}

/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
  let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};
const delsHeader = () => {
  messageBox().then(async () => {
    await delTableList(ids.value)
  }).catch(e => { })
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange = async ({ e, type }) => {
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
    obj.page = 1
    obj.limit = e
  }
  await tableList()
};
// 弹窗
const dialogVisible = ref(false);

const handleClose = (done) => {
  dialogVisible.value = false;
};

const obj = reactive({
  school_id: localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
});
const tableData = ref([])
const tableList = async () => {
  loading()
  const data = await studentList(obj)
  if (data.code == 200) {
    data.data.data.forEach(e => {
      e.status == 1 ? e.statuss = '現有' : e.statuss = '過往'
      e.sex == 1 ? e.sexs = '男' : e.sexs = '女'
    });
    page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    tableData.value = data.data.data
  }
  closeLoading()
}


//  link() {
//     let {
//       href
//     } = this.$router.resolve('/studentInfo')
//     return `${window.location.origin}/${href}`
//   }

const { toClipboard } = useClipboard()
const copy = async () => {
  try {
    await toClipboard(link.value)
    message('已復製')
  } catch (e) {
    console.error(e)
  }
}
const link = ref('')
link.value = `${window.location.origin}/#/studentInfo`


const addConfirm = () => {
  dialogValue.value = false
  tableList()
}
const pageRefresh = async () => {
  await tableList()
}
const studentTypeList = ref([])
const studentTypes = async () => {
  loading()
  let obj = {
    limit: 100
  }
  const data = await studentType(obj)
  if (data.code == 200) {
    data.data.data.forEach(e => { e.label = e.name, e.value = e.id })
    studentTypeList.value = data.data.data
  }
  closeLoading()
}
import { useRouter, useRoute } from "vue-router";
//獲取時間表學生列表信息
const route = useRoute();
// 時間表獲取學生信息

const getinfo = async (e) => {
  let objData = {
    school_id: localStorage.getItem('school_id'),
    id: e
  }
  const data = await studentList(objData)
  if (data.code == 200) {
    data.data.data.forEach(e => {
      e.status == 1 ? e.statuss = '現有' : e.statuss = '過往'
      e.sex == 1 ? e.sexs = '男' : e.sexs = '女'
    });
    await studentTypes()
    activeName.value = 'Information'
    dialogValue.value = true;
    buttonType.value = 'edit'
    const { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact } = data.data.data[0]
    echo.value = { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact }
    echo.value.password = ''
    rules.password = [{ required: false }]
  }
}

// 時間表獲取學生調堂
const tableDataDT = ref([])
const getdiaotang = async (e) => {
  console.log(e);
  let objData = {
    school_id: localStorage.getItem('school_id'),
    id: e
  }
  echo.value = {
    student_id: e
  }
  dialogValue.value = true;
  buttonType.value = 'edit'
  activeName.value = 'hall'
  let form = {
    student_id: e
  }
  let page = { page: 1, limit: 10, total: 0, page_size: [10, 20, 30] }
  Object.assign(form, page)
  const result = await getSign(form)
  if (result.code == 200) {
    TuningHallRef.value.page.total = result.data.total
    result.data.data.map(e => {
      if (e.date && e.time1) {
        e.courseTime = e.date + '-' + e.time1
      } else {
        e.courseTime = e.start_time + '-' + e.end_time.split(' ')[1]
      }
    })
    result.data.data.map(e => {
      e.name = e.course?.name
    })
    tableDataDT.value = result.data.data
  }
  timeStudengt(objData)
  // const data = await studentList(objData)
  // if (data.code == 200) {
  //   data.data.data.forEach(e => {
  //     e.status == 1 ? e.statuss = '現有' : e.statuss = '過往'
  //     e.sex == 1 ? e.sexs = '男' : e.sexs = '女'
  //   });
  //   await studentTypes()

  //   dialogValue.value = true;
  //   buttonType.value = 'edit'
  //   const { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact } = data.data.data[0]
  //   echo.value = { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact }
  //   echo.value.password = ''
  //   rules.password = [{ required: false }]
  // }
}
// 時間表使用套票
const tableDataTP = ref([])
const gettickets = async (e) => {
  echo.value = {
    student_id: e
  }
  dialogValue.value = true;
  buttonType.value = 'edit'
  activeName.value = 'ticket'
  let form = {
    student_id: e
  }
  let page = { page: 1, limit: 10, total: 0, page_size: [10, 20, 30] }
  Object.assign(form, page)

  const result = await getTickets(form)
  if (result.code == 200) {
    tableDataTP.value = result.data.data
    ticketRef.value.page.total = result.data.total
  }
  let objData = {
    school_id: localStorage.getItem('school_id'),
    id: e
  }
  timeStudengt(objData)
}
const timeStudengt = async (objData) => {
  const data = await studentList(objData)
  if (data.code == 200) {
    data.data.data.forEach(e => {
      e.status == 1 ? e.statuss = '現有' : e.statuss = '過往'
      e.sex == 1 ? e.sexs = '男' : e.sexs = '女'
    });
    await studentTypes()
    dialogValue.value = true;
    buttonType.value = 'edit'
    const { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact } = data.data.data[0]
    echo.value = { id, name, mobile, email, address, ename, source, sex, status, num, birthday, identity, student_type_id, education, card_number, username, remark, contact }
    echo.value.password = ''
    rules.password = [{ required: false }]
  }
}
onMounted(() => {
  const id = localStorage.getItem('showStudentId')
  if (route.query.id && id && route.query.type == 'detail') {
    getinfo(id)
    localStorage.removeItem('showStudentId')
  }
  if (route.query.id && id && route.query.type == 'diaotang') {
    getdiaotang(id)
    localStorage.removeItem('showStudentId')
  }
  if (route.query.id && id && route.query.type == 'usetickets') {
    gettickets(id)
    localStorage.removeItem('showStudentId')
  }
  tableList()
})
</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.box {
  padding: 16px 33px;
}

.button {
  color: #fff;
}

// .el-tabs--border-card{
//   border: none;
// }
// .tabs{
//   :deep(.el-tabs__item){
//   border: 1px solid #e5e7eb !important;
//   margin-top: 1px;
//   }
//   :deep(.el-tabs__item:first-child){
//   margin: 0;
//   }
// }
// .el-tabs--border-card>.el-tabs__header .el-tabs__item:first-child{
//   margin-left: 0;
// }</style>